package com.idbk.chargestation.adapter;

import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.idbk.chargestation.R;
import com.idbk.chargestation.activity.pile.ActivityPointDetail;
import com.idbk.chargestation.api.APIForPoint;
import com.idbk.chargestation.base.BaseActivity;
import com.idbk.chargestation.bean.JsonBase;
import com.idbk.chargestation.bean.JsonComment;
import com.idbk.chargestation.bean.JsonReplysList;
import com.idbk.chargestation.net.EHttpResponse;
import com.idbk.chargestation.util.Const;
import com.idbk.chargestation.util.DateUtils;
import com.idbk.chargestation.util.GsonUtils;
import com.idbk.chargestation.view.NestedListView;

import java.util.List;

//import com.idbk.chargestation.activity.pile.ActivityPointDetail;

/**
 * 我的评论适配器
 *
 * @author liangzw, lupc
 */
public class MyCommentAdapter extends BaseAdapter {

    public final static String TAG = MyCommentAdapter.class.getSimpleName();

    private List<JsonComment> mData;
    private Context mContext;
    private LayoutInflater mInflater;

    private ProgressDialog mProgressDialog;//等待框
    private StringRequest mRequest;//当前请求(配合等待框)

    public MyCommentAdapter(List<JsonComment> list, Context context) {
        mData = list;
        mContext = context;
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public Object getItem(int position) {
        return mData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    private final class ViewHolder {
        View mParent;

        RatingBar mRatingComment;
        TextView tvPointName, tvContent, tvTime;

        NestedListView mNListView;//回复列表

        View mViewReplyListFoot;
        TextView mTextReplyListFoot;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.item_my_comment, parent, false);

            holder.mParent = convertView;

            holder.mRatingComment = (RatingBar) convertView.findViewById(R.id.ratingbar_comment);

            holder.tvPointName = (TextView) convertView.findViewById(R.id.textview_point_name);
            holder.tvContent = (TextView) convertView.findViewById(R.id.textview_comment_content);
            holder.tvTime = (TextView) convertView.findViewById(R.id.textview_comment_time);

            holder.mNListView = (NestedListView) convertView.findViewById(R.id.nestedlistview_replies);

            holder.mViewReplyListFoot = mInflater.inflate(R.layout.item_comment_reply_foot, holder.mNListView, false);
            holder.mTextReplyListFoot = (TextView) holder.mViewReplyListFoot.findViewById(R.id.textview_item_comment_reply_foot);
            holder.mNListView.addFooterView(holder.mViewReplyListFoot);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        bindView(position, holder);

        return convertView;
    }

    private void bindView(final int position, ViewHolder holder) {
        final JsonComment item = mData.get(position);
        //评分
        holder.mRatingComment.setRating(item.mark);
        //时间
        holder.tvTime.setText(DateUtils.getTimeDifference(item.commentDate));
        //内容
        holder.tvContent.setText(item.comment);
        //充电点名称
        holder.tvPointName.setText(item.pointName);
        //回复列表
        bindReply(item, holder);

        //绑定事件
        holder.mParent.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                String[] items = {"复制", "删除", "进入充电点"};
                new AlertDialog.Builder(mContext)
                        .setItems(items, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (which == 0) {
                                    //复制
                                    ClipboardManager cmb = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
                                    ClipData clip = ClipData.newPlainText(item.getName(), item.comment);
                                    cmb.setPrimaryClip(clip);
                                    Toast.makeText(mContext, "已复制", Toast.LENGTH_SHORT).show();
                                } else if (which == 1) {
                                    //删除
                                    deleteComment(position, item.id);
                                } else if (which == 2) {
                                    //进入充电点
                                    Intent intent = new Intent(mContext, ActivityPointDetail.class);
                                    intent.putExtra(Const.KEY_ID, item.pointId);
                                    mContext.startActivity(intent);
                                }
                            }
                        })
                        .create()
                        .show();
            }
        });
    }

    private void bindReply(final JsonComment item, final ViewHolder hold) {
        //这个标志 只是在第一此加载的时候判断 是否需要向服务器请求数据
        if (item.replys != null && item.replys.size() > 0) {
            hold.mNListView.setVisibility(View.VISIBLE);
            final PointCommentReplyAdapter adapter = new PointCommentReplyAdapter(
                    mContext, item.id, item.replys);
            adapter.setmOnDeleteListener(new PointCommentReplyAdapter.OnDeleteListener() {

                @Override
                public void onDelete(boolean result) {
                    if (result) {
                        Log.d(TAG, "onDelete  result true");
                    }
                }
            });
            adapter.setmOnAddListener(new PointCommentReplyAdapter.OnAddListener() {

                @Override
                public void onAdd(boolean result) {
                    if (result) {
                        notifyDataSetChanged();
                    }
                }
            });
            //如果一开始的总数小于初始值，则不显示foot
            if (item.replyCount <= JsonComment.PAGE_SIZE_REPLYS) {
                if (hold.mNListView.getFooterViewsCount() > 0) {
                    hold.mNListView.removeFooterView(hold.mViewReplyListFoot);
                }
            } else {
                if (hold.mNListView.getFooterViewsCount() < 1) {
                    hold.mNListView.addFooterView(hold.mViewReplyListFoot);
                }
                //根据总条数和剩余显示数据来决定 foot的视图
                refreshReplyListFoot(adapter, item, hold);
            }
            //
            hold.mNListView.setAdapter(adapter);
        } else {
            hold.mNListView.setVisibility(View.GONE);
        }
    }

    private void refreshReplyListFoot(
            final PointCommentReplyAdapter adapter,
            final JsonComment item,
            final ViewHolder hold
    ) {
        //根据剩余回复数来
        if (item.getRemainReplys() > 0) {
            hold.mTextReplyListFoot.setText("加载更多");
            hold.mTextReplyListFoot.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    showProgressDialog();
                    final int pageIndex = item.mPageIndex + 1;
                    Log.d(TAG, "评论id:" + item.id + " 页码：" + pageIndex);
                    mRequest = APIForPoint.getPointCommentReplys(item.id, pageIndex, JsonComment.PAGE_SIZE_REPLYS, new EHttpResponse() {

                        @Override
                        public void onEResponse(String response) {
                            JsonReplysList result = GsonUtils.toBean(JsonReplysList.class, response);
                            if (BaseActivity.handleResponseStatus(mContext, result)) {
                                Log.d(TAG, "评论回复 数据返回成功");
                                if (result.replyItems != null && result.replyItems.size() > 0) {
                                    item.addReplys(result.total, pageIndex, result.replyItems);
                                    adapter.notifyDataSetChanged();
                                }
                                refreshReplyListFoot(adapter, item, hold);
                            }
                        }

                        @Override
                        public void onEErrorResponse(VolleyError error) {
                            Toast.makeText(mContext, "错误：服务器返回数据失败！", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onEFinish() {
                            super.onEFinish();
                            dismissProgressDialog();
                        }

                    });
                }
            });
        } else {
            hold.mTextReplyListFoot.setText("没有更多了");
            hold.mTextReplyListFoot.setOnClickListener(null);
        }
    }

    private void deleteComment(final int position, int commentId) {
        showProgressDialog();
        mRequest = APIForPoint.deleteComment(commentId, new EHttpResponse() {

            @Override
            public void onEResponse(String response) {
                JsonBase result = GsonUtils.toBean(JsonBase.class, response);
                if (BaseActivity.handleResponseStatus(mContext, result)) {
                    //删除成功后，刷新
                    mData.remove(position);
                    notifyDataSetChanged();
                }
            }

            @Override
            public void onEErrorResponse(VolleyError error) {
                Toast.makeText(mContext, "错误：服务器返回数据失败！", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onEFinish() {
                // TODO Auto-generated method stub
                super.onEFinish();
                dismissProgressDialog();
            }

        });
    }

    private void showProgressDialog() {
        dismissProgressDialog();
        mProgressDialog = ProgressDialog.show(mContext, null, "提交中...", true, true, new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                if (mRequest != null) {
                    mRequest.cancel();
                }
            }
        });
        mProgressDialog.setCanceledOnTouchOutside(false);
    }

    private void dismissProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }
}
